package com.android.clinic.app.ui.main;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.android.clinic.app.ClinicApplication;
import com.android.clinic.app.R;
import com.android.clinic.app.adapter.HomeBannerAdapter;
import com.android.clinic.app.adapter.HomeClassifyAdapter;
import com.android.clinic.app.adapter.HomeDynamicAdapter;
import com.android.clinic.app.adapter.HomeRecommendAdapter;
import com.android.clinic.app.adapter.TopCoverAdapter;
import com.android.clinic.app.base.BaseFragment;
import com.android.clinic.app.entity.BannerInfo;
import com.android.clinic.app.entity.DepartmentInfo;
import com.android.clinic.app.entity.DoctorInfo;
import com.android.clinic.app.entity.DynamicInfo;
import com.android.clinic.app.http.HttpClient;
import com.android.clinic.app.http.base.BaseObserver;
import com.android.clinic.app.http.utils.RxObservableUtils;
import com.android.clinic.app.ui.personal.RenewalFeeMemberActivity;
import com.android.clinic.app.ui.widget.UIAlertView;
import com.android.clinic.app.utils.AppApplicationManager;
import com.android.clinic.app.utils.LocalDataUtils;
import com.android.clinic.app.utils.Toasty;
import com.android.clinic.app.utils.Utils;
import com.qiangxi.checkupdatelibrary.dialog.UpdateDialog;
import com.qiangxi.checkupdatelibrary.utils.ApplicationUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.qiangxi.checkupdatelibrary.dialog.UpdateDialog.UPDATE_DIALOG_PERMISSION_REQUEST_CODE;

/**
 * Created by cheng on 2018/1/26.
 * 首页
 */
public class HomeFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    private SwipeRefreshLayout swipeRefreshLayout;

    private HomeClassifyAdapter classifyAdapter;
    private HomeBannerAdapter bannerAdapter;
    private HomeRecommendAdapter recommendAdapter;

    private UpdateDialog mUpdateDialog;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        RecyclerView mRecyclerView = (RecyclerView) bindView.findViewById(R.id.recyclerView);
        swipeRefreshLayout = (SwipeRefreshLayout) bindView.findViewById(R.id.swipe_container);
        swipeRefreshLayout.setOnRefreshListener(this);

        VirtualLayoutManager layoutManager = new VirtualLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(layoutManager);

        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        mRecyclerView.setRecycledViewPool(viewPool);
        viewPool.setMaxRecycledViews(0, 20);
        mRecyclerView.setItemViewCacheSize(5);

        List<DelegateAdapter.Adapter> adapterList = new LinkedList<>();

        // 顶部广告图
        TopCoverAdapter topCoverAdapter = new TopCoverAdapter(getActivity());
        adapterList.add(topCoverAdapter);
        // 科室分类
        classifyAdapter = new HomeClassifyAdapter(getActivity());
        adapterList.add(classifyAdapter);
        // 广告
        bannerAdapter = new HomeBannerAdapter(getActivity());
        adapterList.add(bannerAdapter);
        // 就诊动态
        HomeDynamicAdapter dynamicAdapter = new HomeDynamicAdapter(getActivity());
        dynamicAdapter.setArrayList(createDynamicData());
        adapterList.add(dynamicAdapter);
        // 名医列表
        recommendAdapter = new HomeRecommendAdapter(getActivity());
        adapterList.add(recommendAdapter);

        DelegateAdapter delegateAdapter = new DelegateAdapter(layoutManager);
        delegateAdapter.setAdapters(adapterList);
        mRecyclerView.setAdapter(delegateAdapter);

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int position = ((VirtualLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
                if (position >= 1) {
                    ((MainActivity) getActivity()).mImmersionBar.statusBarColorTransform(R.color.colorPrimaryDark)
                            .barAlpha(1.0f)
                            .init();
                } else {
                    ((MainActivity) getActivity()).mImmersionBar.statusBarColorTransform(R.color.colorPrimaryDark)
                            .barAlpha(0f)
                            .init();
                }
            }
        });
    }

    @Override
    protected void loadData() {
        getListBanner();
        getDepartment();
        getDoctorRest();
        checkVersionUpdate();
        checkMemberIsExpired();
    }

    /**
     * 获取科室信息
     */
    private void getDepartment() {
        HttpClient.getHttpService().getDepartment()
                .compose(RxObservableUtils.applySchedulers())
                .subscribe(new BaseObserver<List<DepartmentInfo>>() {
                    @Override
                    public void onSuccess(List<DepartmentInfo> departmentInfo) {
                        LocalDataUtils.objectMap.put(HomeClassifyAdapter.REQ_CLASSIFY, departmentInfo);
                        classifyAdapter.notifyClassify();
                    }

                    @Override
                    public void onFailure(String message) {
                        Toasty.showShort(getActivity(), message);
                    }
                });
    }

    /**
     * 获取名医推荐
     */
    private void getDoctorRest() {
        HttpClient.getHttpService().getHomeDoctor()
                .compose(RxObservableUtils.applySchedulers())
                .subscribe(new BaseObserver<List<DoctorInfo>>() {
                    @Override
                    public void onSuccess(List<DoctorInfo> recommendInfo) {
                        String[] stringList = mActivity.getResources().getStringArray(R.array.homeStringList);
                        int size = recommendInfo.size();
                        for (int i = 0; i < size; i++) {
                            recommendInfo.get(i).setMotto(stringList[i]);
                        }
                        swipeRefreshLayout.setRefreshing(false);
                        recommendAdapter.setRecommendList(recommendInfo);
                    }

                    @Override
                    public void onFailure(String message) {
                        swipeRefreshLayout.setRefreshing(false);
                        Toasty.showShort(getActivity(), message);
                    }
                });
    }

    /**
     * 获取轮播图
     *
     * @return
     */
    private void getListBanner() {
         HttpClient.getHttpService().getBannerListAll()
                 .compose(RxObservableUtils.applySchedulers())
                 .subscribe(new BaseObserver<List<BannerInfo>>() {
                     @Override
                     public void onSuccess(List<BannerInfo> bannerInfo) {
                         bannerAdapter.setBannerData(bannerInfo);
                     }

                     @Override
                     public void onFailure(String message) {
                         Toasty.showShort(getActivity(), message);
                     }
                 });
    }

    private ArrayList<DynamicInfo> createDynamicData() {
        ArrayList<DynamicInfo> dynamicInfoList = new ArrayList<>();
        dynamicInfoList.add(new DynamicInfo("1", "爱帮诊为患者王景富邀请专家会诊"));
        dynamicInfoList.add(new DynamicInfo("2", "爱帮诊为患者张俊涛邀请专家会诊"));
        dynamicInfoList.add(new DynamicInfo("3", "爱帮诊为患者陈敏邀请专家会诊"));
        dynamicInfoList.add(new DynamicInfo("4", "爱帮诊为患者刘福寿邀请专家会诊"));
        dynamicInfoList.add(new DynamicInfo("5", "爱帮诊为患者吴玉文邀请专家会诊"));
        dynamicInfoList.add(new DynamicInfo("6", "爱帮诊为患者陈宏邀请专家会诊"));
        return dynamicInfoList;
    }

    /**
     * 检查会员是否过期
     */
    private void checkMemberIsExpired() {
        // 0:永久用户;1:续费用户
        if (null != ClinicApplication.getUserInfo()
                && ClinicApplication.getUserInfo().getAlwaysFree() == 1)  {
            // 判断会员时间是否已经过期, 过期了提示续费
            if (Utils.compareToDate(ClinicApplication.getUserInfo().getDueDate())) {
                UIAlertView.alertDialog(getActivity(), "操作提示",
                        "会员卡已过期, 请续费", new UIAlertView.OnThemeDialogListener() {
                            @Override
                            public void OnDismissButton() {

                            }

                            @Override
                            public void OnSureButton() {
                                startActivity(new Intent(getActivity(), RenewalFeeMemberActivity.class));
                            }
                        }, "去续费", "取消");
            }
        }
    }

    /**
     * 版本更新检测
     */
    private void checkVersionUpdate() {
        Call<ResponseBody> call = HttpClient.getHttpService().getVersion();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String result = response.body().string();
                    JSONObject json = new JSONObject(result);
                    String version = json.getString("version");
                    String url = json.getString("url");
                    String content = json.getString("content");
                    String updateTime = json.getString("updateTime");
                    String versionName = json.getString("versionName");
                    if (!String.valueOf(AppApplicationManager.getVersionCode(getActivity())).equals(version)) {
                        versionUpdate(url, content, updateTime, versionName);
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    /**
     * 版本更新对话框
     *
     * @param url
     * @param content
     * @param updateTime
     */
    private void versionUpdate(String url, String content, String updateTime, String versionName) {
        mUpdateDialog = new UpdateDialog(getActivity(), ((MainActivity) (getActivity())).getVisibleFragment());
        mUpdateDialog
                .setDownloadUrl(url)
                .setTitle(AppApplicationManager.getApplicationName(getActivity()) + "APP有更新了!")
                .setReleaseTime(updateTime)
                .setVersionName(versionName)
                .setUpdateDesc(content)
                .setFileName("aibangzhen.apk")
                .setFilePath(Environment.getExternalStorageDirectory().getPath() + "/fucai")
                .setShowProgress(true)
                .setIconResId(R.mipmap.icon_app_logo)
                .setAppName(ApplicationUtil.getApplicationName(getActivity())).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (requestCode == UPDATE_DIALOG_PERMISSION_REQUEST_CODE) {
                //进行下载操作
                if (mUpdateDialog != null) {
                    mUpdateDialog.download();
                }
            } else {
                //用户不同意,提示用户,如下载失败,因为您拒绝了相关权限
                Toast.makeText(getActivity(), getResources().getString(R.string.permission_need), Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            bannerAdapter.startBanner();
        } else {
            bannerAdapter.stopBanner();
        }
        super.onHiddenChanged(hidden);
    }

    @Override
    public void onPause() {
        super.onPause();
        bannerAdapter.stopBanner();
    }

    @Override
    public void onResume() {
        super.onResume();
        bannerAdapter.startBanner();
    }

    @Override
    public void onRefresh() {
        getDoctorRest();
    }

}
